package com.inhim.pjhim.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.PixelFormat;
import android.graphics.Shader;
import android.os.Build;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.inhim.pjhim.R;
import com.inhim.pjhim.activity.RadioActivity;
import com.inhim.pjhim.app.BaseActivity;
import com.inhim.pjhim.app.MyApplication;
import com.inhim.pjhim.dowloadfile.download.MyBusinessInfoDid;
import com.inhim.pjhim.entity.ReaderInfo;
import com.inhim.pjhim.utils.GlideUtils;


/**
 * Created by xiang on 2016/12/28.
 *
 * im悬浮窗视图
 */

public class ChatView extends RelativeLayout{

    // 悬浮栏位置
    private final static int LEFT = 0;
    private final static int RIGHT = 1;
    private final static int TOP = 3;
    private final static int BUTTOM = 4;

    private int dpi;
    private int screenHeight;
    private int screenWidth;
    private WindowManager.LayoutParams wmParams;
    private WindowManager wm;
    //private float x, y;
    //private float mTouchStartX;
    private float y;
    private float mTouchStartY;
    private boolean isScroll;
    private CircleImageView civ_view;
    private FlashTextView tv_name;
    private ReaderInfo.Reader readerInfo;
    private MyBusinessInfoDid businessInfoDid;
    private Activity activity;
    private int mReaderId;

    public ChatView(Activity activity, ReaderInfo.Reader readerInfo, MyBusinessInfoDid businessInfoDid,int readerId) {
        super(activity);
        this.mReaderId=readerId;
        this.activity=activity;
        this.readerInfo=readerInfo;
        this.businessInfoDid=businessInfoDid;
        View layou=LayoutInflater.from(activity).inflate(R.layout.view_audio_suspended, this);
        civ_view=layou.findViewById(R.id.civ_view);
        tv_name=layou.findViewById(R.id.tv_name);
        setTextViewStyles(tv_name);
        if(businessInfoDid!=null){
            GlideUtils.displayFromUrl(businessInfoDid.getCover(),civ_view,MyApplication.getContext());
            tv_name.setText(businessInfoDid.getTitle());
        }else if(readerInfo!=null){
            GlideUtils.displayFromUrl(readerInfo.getCover(),civ_view,MyApplication.getContext());
            //Glide.with(MyApplication.getContext()).load(readerInfo.getCover()).into(civ_view);
            tv_name.setText(readerInfo.getTitle());
        }
        wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        //通过像素密度来设置按钮的大小
        dpi = dpi(dm.densityDpi);
        //屏宽
        screenWidth = wm.getDefaultDisplay().getWidth();
        //屏高
        screenHeight = wm.getDefaultDisplay().getHeight();
        //布局设置
        wmParams = new WindowManager.LayoutParams();
        // 设置window type
        //wmParams.type = WindowManager.LayoutParams.TYPE_APPLICATION;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            wmParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        }
        wmParams.format = PixelFormat.RGBA_8888; // 设置图片格式，效果为背景透明
        wmParams.gravity = Gravity.RIGHT | Gravity.TOP;
        // 设置Window flag
        wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        wmParams.width = dpi;
        wmParams.height = dpi;
        wmParams.y = (screenHeight - dpi) >> 1;
        wm.addView(this, wmParams);
        hide();
    }

    public void setView(String Cover,String title){
        GlideUtils.displayFromUrl(Cover, civ_view, MyApplication.getContext());
        tv_name.setText(title);
    }

    public void setTextViewStyles(TextView text){

        LinearGradient mLinearGradient =new LinearGradient(0, 0, 0, text.getPaint().getTextSize()*2, Color.parseColor("#FFFFFF"), Color.parseColor("#0A8EA0"), Shader.TileMode.CLAMP);

        text.getPaint().setShader(mLinearGradient);

        text.invalidate();

    }

    /**
     * 根据密度选择控件大小
     *
     */
    private int dpi(int densityDpi) {
        if (densityDpi <= 120) {
            return 236;
        } else if (densityDpi <= 160) {
            return 248;
        } else if (densityDpi <= 240) {
            return 272;
        } else if (densityDpi <= 320) {
            return 296;
        }
        return 308;
    }

    public void show() {
        if (isShown()) {
            return;
        }
        setVisibility(View.VISIBLE);
    }


    public void hide() {
        setVisibility(View.GONE);
    }

    public void destory() {
        mMainHander.removeCallbacksAndMessages(null);
        hide();
        wm.removeViewImmediate(this);
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // 获取相对屏幕的坐标， 以屏幕左上角为原点
        //x = event.getRawX();
        y = event.getRawY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // setBackgroundDrawable(openDrawable);
                // invalidate();
                // 获取相对View的坐标，即以此View左上角为原点
               // mTouchStartX = event.getX();
                mTouchStartY = event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                if (isScroll) {
                    updateViewPosition();
                } else {
                    // 当前不处于连续滑动状态 则滑动小于图标1/3则不滑动
                    /*if (Math.abs(mTouchStartX - event.getX()) > dpi / 3
                            || Math.abs(mTouchStartY - event.getY()) > dpi / 3) {*/
                    if (Math.abs(mTouchStartY - event.getY()) > dpi / 3) {
                        updateViewPosition();
                    } else {
                        break;
                    }
                }
                isScroll = true;
                break;
            case MotionEvent.ACTION_UP:
                // 拖动
                if (isScroll) {
                    autoView();
                    // setBackgroundDrawable(closeDrawable);
                    // invalidate();
                } else {
                    // 当前显示功能区，则隐藏
                    // setBackgroundDrawable(openDrawable);
                    // invalidate();
                    if(mMainHander==null){
                        mMainHander=new Handler();
                    }
                    mMainHander.removeCallbacksAndMessages(null);
                    mMainHander.postDelayed(() -> {
                        Intent intent=new Intent(activity, RadioActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                        if(businessInfoDid!=null){
                            intent.putExtra("result",businessInfoDid);
                        }else if(readerInfo!=null){
                            intent.putExtra("readerInfo",readerInfo);
                        }else{
                            intent.putExtra("ReaderId", mReaderId);
                        }
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.putExtra("TAG","ChatView");
                        activity.startActivity(intent);
                    },500);

                }
                isScroll = false;
                //mTouchStartX = mTouchStartY = 0;
                break;
        }
        return super.onTouchEvent(event);
    }
    private Handler mMainHander=new Handler();
    /**
     * 自动移动位置
     */
    private void autoView() {
        // 得到view在屏幕中的位置
        int[] location = new int[2];
        getLocationOnScreen(location);
        //左侧
        /*if (location[0] < screenWidth / 2 - getWidth() / 2) {
            updateViewPosition(LEFT);
        } else {
            updateViewPosition(RIGHT);
        }*/
        //这里的LEFT和Right是相对于wmParams.gravity = Gravity.RIGHT | Gravity.TOP;属性来说的
        updateViewPosition(LEFT);
    }

    /**
     * 手指释放更新悬浮窗位置
     *
     */
    private void updateViewPosition(int l) {
        switch (l) {
            case LEFT:
                wmParams.x = 0;
                break;
            case RIGHT:
                int x = screenWidth - dpi;
                wmParams.x = x;
                break;
            case TOP:
                wmParams.y = 0;
                break;
            case BUTTOM:
                wmParams.y = screenHeight - dpi;
                break;
        }
        wm.updateViewLayout(this, wmParams);
    }

    // 更新浮动窗口位置参数
    private void updateViewPosition() {
        //wmParams.x = (int) (x - mTouchStartX);
        //是否存在状态栏（提升滑动效果）
        // 不设置为全屏（状态栏存在） 标题栏是屏幕的1/25
        wmParams.y = (int) (y - mTouchStartY - screenHeight / 25);
        wm.updateViewLayout(this, wmParams);
    }
}
